package com.itheima.service;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyDetailService implements UserDetailsService {

    //注入接口
    @Reference
    private UserService userService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username){

        //从缓存中获取用户信息
        org.springframework.security.core.userdetails.User securityUser =
                (org.springframework.security.core.userdetails.User) redisTemplate.opsForValue().get(username);

        //判断缓存是否存在
        if (securityUser==null) {
            //第一次登录

            //根据用户名查询到对应的User对象,以及对应的属性:角色集合以及角色对应的权限集合
            User user = userService.findUserByUsername(username);

            //创建存储权限和角色的集合
            List<GrantedAuthority> list = new ArrayList<>();

            //遍历user的角色集合
            for (Role role : user.getRoles()) {

                //将角色的keyword添加到集合中
                list.add(new SimpleGrantedAuthority(role.getKeyword()));

                //遍历每个角色的权限集合
                for (Permission permission : role.getPermissions()) {

                    //将权限的keyword添加到集合中
                    list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                }
            }
            securityUser = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), list);
            //存到redis中 120秒
            redisTemplate.opsForValue().set(username, securityUser,120, TimeUnit.SECONDS);
        }
        return securityUser;
    }



}
